package com.elm.service.impl;

import com.elm.ElmSpringbootApplication;
import com.elm.mapper.BusinessMapper;
import com.elm.mapper.PersonMapper;
import com.elm.mapper.UserAuthorityMapper;
import com.elm.mapper.UserMapper;
import com.elm.po.Authority;
import com.elm.po.Business;
import com.elm.po.Food;
import com.elm.po.Person;
import com.elm.po.User;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

	private final ElmSpringbootApplication elmSpringbootApplication;

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private PersonMapper personMapper;
	@Autowired
	private BusinessMapper businessMapper;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private UserAuthorityMapper userAuthorityMapper;

	UserServiceImpl(ElmSpringbootApplication elmSpringbootApplication) {
		this.elmSpringbootApplication = elmSpringbootApplication;
	}

	private String getCurrentUserName() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUsernameFromToken(token);
	}

	private String getCurrentUserType() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUserTypeFromToken(token);
	}
	@Override
	 public String getAuthority(){
		 int userId=userMapper.getUserIdByName(getCurrentUserName());
		 return userAuthorityMapper.getAuthorityById(userId);
	 }


	@Override
	public User getUserByNameByPass(String username, String password) {
		// 登录验证，公开接口
		return userMapper.getUserByNameByPass(username, password);
	}

	@Override
	public User createUser(User user) {
		// 执行插入，insertCart会自动为cart的id字段赋值（自增ID）
		int rows = userMapper.createUser(user);
		if (rows <= 0) {
			throw new RuntimeException("添加user失败");
		}
		// 直接通过自增ID查询刚刚插入的记录
		// 插入权限
		List<Authority> authorities = user.getAuthorities();
        int admin=0,business=0,User=0;
        if (authorities != null && !authorities.isEmpty()) {
            for (Authority auth : authorities) {
                if(auth.getName().equals("ADMIN")) admin++;
                if(auth.getName().equals("BUSINESS")) business++;
                if(auth.getName().equals("USER")) User++;
            }
            if(admin!=0) userAuthorityMapper.addUserAuthority(user.getId(), "ADMIN");
            else if(business!=0) userAuthorityMapper.addUserAuthority(user.getId(), "BUSINESS");
            else if(User!=0) userAuthorityMapper.addUserAuthority(user.getId(), "USER");
        }
		Person person = new Person();
		person.setId(user.getId());
		personMapper.createPerson(person);
		return userMapper.getUserById(user.getId());
	}

	@Override
	public User getUserByName(String username) {
		return userMapper.getUserByName(username);
	}

	@Override
	public User getUserByName() {
		// 检查用户是否存在，公开接口
		return userMapper.getUserByName(getCurrentUserName());
	}

	// ADMIN与本人专属：修改密码
	@Override
	public int updatePassword(User user) {
		if (!user.getUsername().equals(getCurrentUserName()) && !getCurrentUserType().equals("ADMIN")) {
			throw new RuntimeException("仅用户本人及ADMIN可修改密码");
		}
		return userMapper.updatePassword(user);
	}

	// ADMIN专属：封禁用户
	@Override
	public User banUser(int targetUserId) {
		if (!"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅管理员可封禁用户");
		}
		// 封禁用户（更新status字段）
		userMapper.updateStatus(targetUserId, "banned");
		return userMapper.getUserById(targetUserId);
	}

	// 商家Boss专属：添加员工
	@Override
	public User addStaff(int staffUserId, int businessId) {
		if (!"BUSINESS".equals(getCurrentUserType()) && !"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅商家老板和ADMIN可添加员工");
		}
		if ("BUSINESS".equals(getCurrentUserType())) {
			// 获取boss所属商家
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
		}
		// 将员工关联到该商家，并设置用户类型为staff
		userMapper.addStaff(staffUserId, businessId);
		return userMapper.getUserById(staffUserId);
	}

	// 商家Boss专属：删除员工
	@Override
	public int deleteStaff(int staffUserId, int businessId) {
		if (!"BUSINESS".equals(getCurrentUserType()) && !"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅商家老板和ADMIN可删除员工");
		}
		if ("BUSINESS".equals(getCurrentUserType())) {
			// 获取boss所属商家
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
		}
		// 将员工关联到该商家，并设置用户类型为staff
		return userMapper.deleteStaff(staffUserId, businessId);
	}

	// 商家Boss专属：获取员工
	@Override
	public List<Person> getAllStaff(int businessId) {
		if (!"BUSINESS".equals(getCurrentUserType()) && !"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅商家老板和ADMIN可获取员工");
		}
		if ("BUSINESS".equals(getCurrentUserType())) {
			// 获取boss所属商家
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(businessMapper.getBusinessById(businessId).getId()));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
		}
		// 将员工关联到该商家，并设置用户类型为staff
		return userMapper.getAllStaff(businessId);
	}

}